package com.demo.practiceui.views.animation;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.Nullable;

/**
 * 仪表盘指针动画
 * 核心知识点：
 * 1. ValueAnimator - 数值动画
 * 2. 插值器 - 控制动画速度曲线
 * 3. 从当前值平滑过渡到目标值
 * 4. 动画监听
 */
public class DashboardAnimView extends View {

    // 数据
    private float currentValue = 0;     // 当前值
    private float targetValue = 65;     // 目标值
    private float maxValue = 100;
    private float minValue = 0;

    // 画笔
    private Paint arcPaint;
    private Paint pointerPaint;
    private Paint textPaint;
    private Paint scalePaint;

    // 尺寸
    private int width;
    private int height;
    private float centerX;
    private float centerY;
    private float radius;

    private float startAngle = 135;
    private float sweepAngle = 270;

    private RectF rectF;
    private Path pointerPath;

    // 动画
    private ValueAnimator valueAnimator;

    public DashboardAnimView(Context context) {
        this(context, null);
    }

    public DashboardAnimView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DashboardAnimView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        arcPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        arcPaint.setStyle(Paint.Style.STROKE);
        arcPaint.setStrokeWidth(30f);
        arcPaint.setStrokeCap(Paint.Cap.ROUND);

        pointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        pointerPaint.setColor(Color.parseColor("#FF5722"));
        pointerPaint.setStyle(Paint.Style.FILL);
        pointerPaint.setShadowLayer(10, 0, 5, Color.parseColor("#80000000"));

        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.setTextSize(56f);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setFakeBoldText(true);

        scalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        scalePaint.setColor(Color.parseColor("#999999"));
        scalePaint.setStrokeWidth(3f);
        scalePaint.setTextSize(24f);
        scalePaint.setTextAlign(Paint.Align.CENTER);

        rectF = new RectF();
        pointerPath = new Path();

        setLayerType(LAYER_TYPE_SOFTWARE, null);

        // 初始动画
        animateToValue(targetValue, 2000);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 500;
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 500;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
        centerX = width / 2f;
        centerY = height / 2f + 30;
        radius = Math.min(width, height) / 2f - 80;

        rectF.set(centerX - radius, centerY - radius,
                centerX + radius, centerY + radius);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawBackgroundArc(canvas);
        drawProgressArc(canvas);
        drawScale(canvas);
        drawPointer(canvas);
        drawCenterCircle(canvas);
        drawValueText(canvas);
    }

    private void drawBackgroundArc(Canvas canvas) {
        arcPaint.setColor(Color.parseColor("#E0E0E0"));
        canvas.drawArc(rectF, startAngle, sweepAngle, false, arcPaint);
    }

    private void drawProgressArc(Canvas canvas) {
        float valueAngle = ((currentValue - minValue) / (maxValue - minValue)) * sweepAngle;

        if (currentValue < 30) {
            arcPaint.setColor(Color.parseColor("#4CAF50"));
        } else if (currentValue < 70) {
            arcPaint.setColor(Color.parseColor("#FFC107"));
        } else {
            arcPaint.setColor(Color.parseColor("#FF5722"));
        }

        canvas.drawArc(rectF, startAngle, valueAngle, false, arcPaint);
    }

    private void drawScale(Canvas canvas) {
        int scaleCount = 10;
        for (int i = 0; i <= scaleCount; i++) {
            float angle = startAngle + (sweepAngle * i / scaleCount);
            float angleRad = (float) Math.toRadians(angle);

            float startX = centerX + (radius - 40) * (float) Math.cos(angleRad);
            float startY = centerY + (radius - 40) * (float) Math.sin(angleRad);
            float endX = centerX + (radius - 55) * (float) Math.cos(angleRad);
            float endY = centerY + (radius - 55) * (float) Math.sin(angleRad);

            canvas.drawLine(startX, startY, endX, endY, scalePaint);

            float value = minValue + (maxValue - minValue) * i / scaleCount;
            float textX = centerX + (radius - 75) * (float) Math.cos(angleRad);
            float textY = centerY + (radius - 75) * (float) Math.sin(angleRad) + 8;
            canvas.drawText(String.format("%.0f", value), textX, textY, scalePaint);
        }
    }

    private void drawPointer(Canvas canvas) {
        float valueAngle = startAngle + ((currentValue - minValue) / (maxValue - minValue)) * sweepAngle;
        float angleRad = (float) Math.toRadians(valueAngle);

        float pointerLength = radius - 60;
        float pointerWidth = 12f;

        float endX = centerX + pointerLength * (float) Math.cos(angleRad);
        float endY = centerY + pointerLength * (float) Math.sin(angleRad);

        float perpAngle1 = angleRad - (float) Math.PI / 2;
        float perpAngle2 = angleRad + (float) Math.PI / 2;

        float side1X = centerX + pointerWidth * (float) Math.cos(perpAngle1);
        float side1Y = centerY + pointerWidth * (float) Math.sin(perpAngle1);
        float side2X = centerX + pointerWidth * (float) Math.cos(perpAngle2);
        float side2Y = centerY + pointerWidth * (float) Math.sin(perpAngle2);

        pointerPath.reset();
        pointerPath.moveTo(endX, endY);
        pointerPath.lineTo(side1X, side1Y);
        pointerPath.lineTo(side2X, side2Y);
        pointerPath.close();

        canvas.drawPath(pointerPath, pointerPaint);
    }

    private void drawCenterCircle(Canvas canvas) {
        pointerPaint.setColor(Color.parseColor("#FF5722"));
        canvas.drawCircle(centerX, centerY, 18, pointerPaint);

        pointerPaint.setColor(Color.WHITE);
        canvas.drawCircle(centerX, centerY, 8, pointerPaint);

        pointerPaint.setColor(Color.parseColor("#FF5722"));
    }

    private void drawValueText(Canvas canvas) {
        canvas.drawText(String.format("%.0f", currentValue), centerX, centerY + 70, textPaint);

        textPaint.setTextSize(28f);
        textPaint.setColor(Color.parseColor("#999999"));
        canvas.drawText("实时数值", centerX, centerY + 105, textPaint);
        
        textPaint.setTextSize(56f);
        textPaint.setColor(Color.parseColor("#333333"));
    }

    /**
     * 动画过渡到目标值
     */
    public void animateToValue(float value, long duration) {
        if (valueAnimator != null) {
            valueAnimator.cancel();
        }

        targetValue = Math.max(minValue, Math.min(maxValue, value));

        valueAnimator = ValueAnimator.ofFloat(currentValue, targetValue);
        valueAnimator.setDuration(duration);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.addUpdateListener(animation -> {
            currentValue = (float) animation.getAnimatedValue();
            invalidate();
        });
        valueAnimator.start();
    }

    /**
     * 设置目标值（默认1秒动画）
     */
    public void setValue(float value) {
        animateToValue(value, 1000);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (valueAnimator != null) {
            valueAnimator.cancel();
        }
    }
}

